// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Fk
import Fk.Pages
import Fk.RoomElement

GraphicsBox {
  id: root

  property var selectedItem: []
  property var generals: []
  property var cards: []
  property string titleName: ""

  title.text: luatr(titleName)
  width: 320
  height: 460

  Rectangle {
    id: body
    anchors.top: parent.top
    anchors.topMargin: 5
    width: parent.width + -20

    color: "#EEEEEE"
    //opacity: .53
    border.color: "#FEF7D6"
    border.width: 3
    radius : 3

    Repeater {
      id: generalRepeater
      model: ListModel {
        id: generals
      }
      
      Photo {
        playerid: model.id
        general: model.general
        deputyGeneral: model.deputyGeneral
        role: model.role
        maxHp: model.maxHp
        hp: model.hp
        state: "candidate"
        screenName: model.screenName
        kingdom: model.kingdom
        selectable : true
        scale: 0.5

        property bool chosen : false
        property int posX : model.posX
        property int posY : model.posY
        property int listIndex : model.listIndex

        x : 100 * (posX - 1) - 25
        y : 125 * (posY - 1 ) - 25

        Image {
          id : generalChosen
          visible: chosen
          source: SkinBank.CARD_DIR + "chosen"
          anchors.bottom: parent.bottom
          anchors.right: parent.right
          anchors.bottomMargin : 20
          anchors.rightMargin : 30
          scale : 1.7
        }
        
        MouseArea {
          anchors.fill: parent
          onClicked: {
            if (chosen) {
              chosen = false;
              selectedItem.splice(selectedItem.indexOf(listIndex), 1);
            } else {
              let ok = true;
              for (let i = 0; i < selectedItem.length; i++) {
                let [thisX, thisY] = getXYfromIndex(selectedItem[i]);
                if (posX !== thisX && posY !== thisY) {
                  ok = false;
                }
              }
              if (ok) {
                chosen = true;
                selectedItem.push(listIndex);
              }
            }
            updateSelectable();
          }
        }

        Component.onCompleted: {
          this.visibleChildren[12].visible = false; // hide role
          this.visibleChildren[14].visible = false; // hide seat
        }
      }
    }

    Repeater {
      id: cardRepeater
      model: ListModel {
        id: cards
      }

      CardItem {
        cid: model.cid
        name: model.name
        suit: model.suit
        number: model.number
        autoBack: false
        selectable: true
        footnote: ""
        footnoteVisible: false
        scale: 0.9

        property bool chosen : false
        property int posX : model.posX
        property int posY : model.posY
        property int listIndex : model.listIndex

        x : 100 * (posX - 1) + 15
        y : 125 * (posY - 1 ) + 30

        Image {
          id : generalChosen
          visible: chosen
          source: SkinBank.CARD_DIR + "chosen"
          anchors.bottom: parent.bottom
          anchors.right: parent.right
          anchors.bottomMargin : 12
          anchors.rightMargin : 5
          scale : 1
        }
        
        MouseArea {
          anchors.fill: parent
          onClicked: {
            if (chosen) {
              chosen = false;
              selectedItem.splice(selectedItem.indexOf(listIndex), 1);
            } else {
              let ok = true;
              for (let i = 0; i < selectedItem.length; i++) {
                let [thisX, thisY] = getXYfromIndex(selectedItem[i]);
                if (posX !== thisX && posY !== thisY) {
                  ok = false;
                }
              }
              if (ok) {
                chosen = true;
                selectedItem.push(listIndex);
              }
            }
            updateSelectable();
          }
        }

      }

    }

  }

  Item {
    id: buttonArea
    anchors.fill: parent
    anchors.bottomMargin: 10
    height: 40

    Row {
      anchors.horizontalCenter: parent.horizontalCenter
      anchors.bottom: parent.bottom
      spacing: 30

      MetroButton {
        id : buttonConfirm
        Layout.fillWidth: true
        text: luatr("OK")
        enabled: selectedItem.length == 3

        onClicked: {
          close();
          roomScene.state = "notactive";
          ClientInstance.replyToServer("", JSON.stringify(selectedItem));
        }
      }

      MetroButton {
        Layout.fillWidth: true
        text: luatr("Cancel")
        enabled: true

        onClicked: {
          root.close();
          roomScene.state = "notactive";
          ClientInstance.replyToServer("", "");
        }
      }

    }
  }

  function updateSelectable() {
    buttonConfirm.enabled = selectedItem.length == 3;
  }

  function getXYfromIndex(i) {
    return [(i % 3) + 1, Math.ceil((i + 1) / 3)]
  }

  function loadData(data) {
    titleName = data[1];

    for (let i = 0; i < data[0].length; i++) {
      let dat = data[0][i];
      if (dat[0] == "general") {
        const player = leval(
          `(function()
            local player = ClientInstance:getPlayerById(${dat[1]})
            return {
              id = player.id,
              general = player.general,
              deputyGeneral = player.deputyGeneral,
              screenName = player.player:getScreenName(),
              kingdom = player.kingdom,
              role = 'hidden',
              maxHp = player.maxHp,
              hp = player.hp,
            }
          end)()`
        );
        [player.posX, player.posY] = getXYfromIndex(i);
        player.listIndex = i;
        generals.append(player);
      } else {
        const card = lcall("GetCardData", dat[1]);
        [card.posX, card.posY] = getXYfromIndex(i);
        card.listIndex = i;
        cards.append(card)
      }
    };
    
  }
}
